package com.jianyun.jyzs.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.UrlConfig;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.update.DownloadUtils;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.Utils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.PromptDialog;
import com.jrmf360.rylib.common.util.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jianyun.jyzs.utils.RceLog;

import cn.jpush.android.api.JPushInterface;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 关于建云助手
 * Created by yangshijun on 2018/5/28.
 */

public class AboutJyzsActivity extends AppCompatActivity {


    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.version_name1)
    TextView versionName1;
    @BindView(R.id.version_name2)
    TextView versionName2;
    @BindView(R.id.updateTime)
    TextView updateTime;
    @BindView(R.id.checkVersion)
    LinearLayout checkVersion;

    private ProgressDialog progressDialog;
    private String enterpriseCode;
    private String gdbVersionCode;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticity_about_gdb);
        UtilsStyle.setStatusBarMode(this,true);
         ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("loading...");
        topText.setText("关于建云助手");
        topBack.setVisibility(View.VISIBLE);
        String versionName = Utils.getVersionName(this);
        versionName1.setText("V" + versionName);
        versionName2.setText("V" + versionName);
        JPushInterface.getAlias(this,202);
        JPushInterface.getAllTags(this,203);
    }

    @OnClick({R.id.topBack, R.id.checkVersion})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.checkVersion:
                initUpdate();
                break;
        }
    }

    String gdbDownLoad = "";

    //检查更新
    private void initUpdate() {
        progressDialog.show();
        RetrofitHelper.builder().create(Api.class).getConfig("GetConfig",enterpriseCode,"jyzs","Android","1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<UrlConfig>() {

                    @Override
                    protected void onResponse(UrlConfig response) {
                        progressDialog.dismiss();
                        RceLog.d("lml",""+response.toString());
                        if (response.isResult()){
                            gdbVersionCode = response.getAndroidVersionCode();
                            gdbDownLoad = response.getAndroidDownLoad();
                            initUpdate(response);
                        }else {
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        RceLog.d("lml",msg);
                        progressDialog.dismiss();
                    }
                });
    }



    private static final int READ_EXTERANL = 100;

    private void initUpdate(UrlConfig urlConfig){
        PromptDialog promptDialog = PromptDialog.newInstance(this, "发现新版本", "立即下载");
        promptDialog.setPromptButtonClickedListener(new PromptDialog.OnPromptButtonClickedListener() {
            @Override
            public void onPositiveButtonClicked() {
                ToastUtil.showNoWaitToast(AboutJyzsActivity.this,"正在下载更新...");
                if (gdbDownLoad!=null){
                    if (ActivityCompat.checkSelfPermission(AboutJyzsActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){
                        new DownloadUtils(AboutJyzsActivity.this).downloadAPK(gdbDownLoad,"建云助手.apk");
                    }else {
                        ActivityCompat.requestPermissions(AboutJyzsActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},READ_EXTERANL);
                    }

                }


            }

            @Override
            public void onNegativeButtonClicked() {
            }
        });
        try{
            int newverCode = 0;
            String newVersion = urlConfig.getAndroidVersionCode();
            if (newVersion != null) newverCode = Integer.parseInt(newVersion);
            int oldverCode = Utils.getVerCode(this);
            String isForceUpdate = urlConfig.getIsForceUpdate();
            if (newverCode > oldverCode) {
                if ("1".equals(isForceUpdate)) {
                    promptDialog.disableCancel();
                }
                promptDialog.show();
            }else {
                ToastUtil.showNoWaitToast(AboutJyzsActivity.this,"已经是最新版本");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ_EXTERANL) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                new DownloadUtils(AboutJyzsActivity.this).downloadAPK(gdbDownLoad,"gongdibao.apk");
            }
        }
    }
}
